// pages/volunteer/intelligence/index.js
const {
  citySubjectList,
  twoMajorList,
} = require('../../../api/api')
const {
  viluntarySmartAdd,
  voluntaryConfigCity
} = require('../../../api/ai')
const {
  filterObj,
  throttle
} = require('../../../utils/util')
const {
  decodeUserInfo
} = require('../../../api/login')
const filterBatch = [{
    id: 1,
    title: "院校地区",
    key: "province",
    type: 'checkbox',
    items: [],
  },
  {
    id: 2,
    title: "办学性质",
    key: "eduType",
    type: 'checkbox',
    items: [{
        id: '公办学校',
        title: "公办学校",
      }, {
        id: '民办学校',
        title: "民办学校",
      },
      {
        id: '中外合作办学',
        title: "中外合作办学",
      },
      {
        id: '内地港澳台合作办学',
        title: "内地港澳台合作办学",
      },
    ],
  },
  {
    id: 3,
    title: "大学特色",
    key: "schoolLabel",
    type: 'checkbox',
    items: [{
        id: 985,
        title: "985",
      }, {
        id: 211,
        title: "211",
      },
      {
        id: '双一流',
        title: "双一流",
      },
      {
        id: '强基计划',
        title: "强基计划",
      }
    ],
  },
  {
    id: 4,
    title: "大学类型",
    key: "schoolType",
    type: 'checkbox',
    items: [{
        id: '综合类',
        title: "综合类",
      }, {
        id: '理工类',
        title: "理工类",
      },
      {
        id: '农林类',
        title: "农林类",
      },
      {
        id: '医药类',
        title: "医药类",
      },
      {
        id: '师范类',
        title: "师范类",
      },
    ],
  },
]

function returnText(array) {
  const texts = array.map((item) => {
    return item.title
  })
  return texts.join('/')
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isRecommend: false,
    status: false,
    scoreTypeList: [],
    level1Name: '本科',
    subjectList: [],
    chooseList: [], //已选择列表
    mainSubject: null,
    checkedList: [],
    score: 0,
    ranking: 0,
    length: 3,
    majorFilterKey: 'majorFilterKey',
    selectedData: {
      volunteer: 'wen',
      category: 0, //查询专业一级
      categoryId: [], //查询专业二级id
      province: [], //院校地区
      eduType: [], //办学性质
      schoolLabel: [], //大学特色
      schoolType: [], //大学类型
      // filterArr: [], //排除属性
    },
    selectorDataList: [{
        id: 1,
        title: "选择大学意向",
        key: "batch",
        type: 'batch',
        value: {},
        items: [],
      },
      {
        id: 2,
        title: "选择专业意向",
        key: "category",
        type: 'checkbox',
        value: {},
        items: [],
      },
      {
        id: 3,
        title: "选择填报意向",
        key: "volunteer",
        type: 'radiobox',
        value: {},
        items: [{
            id: 'chong',
            title: '冲击型',
          },
          {
            id: 'wen',
            title: '稳妥型',
            checked: true
          }, {
            id: 'bao',
            title: '保守型',
          }, {
            id: 'all',
            title: '自定义',
          }
        ],
      },
    ],
    filterBatch: filterBatch,
    filterRouteKey: 'volunteerFilters',
    selectedKey: 'category',
    categoryList: [],
    visible: false,
    loading: false,
    percentage: 0,
    timer: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (options.params) {
      var params = JSON.parse(decodeURIComponent(options.params))
      params.secondSelectChar = params.secondSelect.replaceAll(',', '/')
      this.setData({
        ...params
      })
      this.getVoluntaryConfigCity()
    }

    const {
      filterRouteKey,
      selectedData
    } = this.data
    wx.setStorageSync(filterRouteKey, selectedData)
    await this.fetchCategory()
    await this.fetchCity()
    this.filterKeyFunc()
  },
  async getVoluntaryConfigCity() {
    const {
      provinceId,
      firstSelect
    } = this.data
    const params = {
      provinceId,
      firstSelect
    }
    const {
      result
    } = await voluntaryConfigCity(params)
    result[0].checked = true
    this.setData({
      scoreTypeList: result,
      currentScoreType: result[0]
    })
  },
  onLoadFunc() {

  },
  async fetchCity() {
    const {
      filterBatch
    } = this.data
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    const eduTypeList = wx.getStorageSync('edu_type') || await getApp().getDictData('edu_type')
    const schoolLabelList = wx.getStorageSync('school_label') || await getApp().getDictData('school_label')
    const schoolTypeList = wx.getStorageSync('school_type') || await getApp().getDictData('school_type')
    filterBatch[0].items = cityList
    filterBatch[1].items = eduTypeList
    filterBatch[2].items = schoolLabelList
    filterBatch[3].items = schoolTypeList
    this.setData({
      filterBatch
    })
  },

  async fetchCategory() {
    const {
      selectorDataList,
      level1Name
    } = this.data
    const params = {
      level1Name: level1Name
    }
    const {
      result
    } = await twoMajorList(params)
    // console.log(result)
    const categoryList = result.map((item) => {
      const children = item.children.map((child) => {
        return {
          title: child.name,
          id: child.specialId
        }
      })
      // children.unshift({
      //   id: 0,
      //   title: '不限'
      // })
      return {
        id: item.id,
        title: item.name,
        children
      };
    })
    categoryList.unshift({
      id: 0,
      title: '全部',
      children: [{
        id: 0,
        title: '不限'
      }]
    })
    this.setData({
      categoryList,
    })
  },
  //修改筛选条件
  filterKeyFunc() {
    const {
      selectorDataList,
      filterRouteKey,
      categoryList,
      filterBatch
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    this.setData({
      volunteer: this.filterKey(selectorDataList, 'volunteer', 'items'),
      major: this.filterKey(categoryList, 'categoryId', 'children'),
      provinceArr: this.filterKey(filterBatch, 'province', 'items'),
      eduType: this.filterKey(filterBatch, 'eduType', 'items'),
      schoolLabel: this.filterKey(filterBatch, 'schoolLabel', 'items'),
      schoolType: this.filterKey(filterBatch, 'schoolType', 'items'),
      filterAttr: this.filterKey(filterBatch, 'filterAttr', 'items'),
      selectedData
    })
    let {
      major,
      provinceArr,
      schoolLabel,
      eduType,
      schoolType
    } = this.data
    provinceArr=[...provinceArr,...schoolLabel,...eduType,...schoolType]
    this.setData({
      provinceText: returnText(provinceArr),
      majorText: returnText(major)
    })

  },
  filterKey(selectData, key, children) {
    const {
      filterRouteKey
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    var value = '';
    var array = []
    selectData.map((cate) => {
      if ((Array.isArray(selectedData[key]))) {
        cate[children].map((item) => {
          if (selectedData[key].indexOf(item.id) >= 0) {
            array.push(item)
          }
        })
      } else {
        cate[children].map((item) => {
          if (item.id == selectedData[key]) {
            value = item
          }
        })
      }
    })
    return value == '' ? array : value
  },

  isRecommend() {
    this.setData({
      isRecommend: !this.data.isRecommend
    })
  },
  checkItem(e) {
    const {
      scoreTypeList,
      levelIndex,
    } = this.data
    const {
      index,
      levelname,
      value
    } = e.currentTarget.dataset
    if (levelIndex == index) return
    scoreTypeList.map((item) => {
      item.checked = false
    })
    scoreTypeList[index].checked = true
    this.setData({
      scoreTypeList,
      level1Name: levelname == '本科批' ? '本科' : '专科（高职）',
      levelIndex: index,
      currentScoreType: value
    })
    this.fetchCategory()
  },

  async onSelectChangedRoute(e) {
    const {
      filterRouteKey
    } = this.data
    wx.setStorageSync(filterRouteKey, {
      ...e.detail
    })
    this.setData({
      ...e.detail
    })
    this.filterKeyFunc()

  },
  confirm: throttle(async function () {
    //  if(this.data.status)return
    //  this.setData({
    //    status:true
    //  })


    const {
      provinceId,
      score,
      selectedData,
      chongCount,
      wenCount,
      baoCount,
      firstSelect,
      secondSelect,
      levelIndex,
      province,
      ranking,
      major,
      currentScoreType
    } = this.data
    let specialtyIds = major.map(e => {
      return e.id
    })
    specialtyIds=specialtyIds.filter(e=>{
      return e.id
    })
    var params = {
      bao: baoCount,
      chong: chongCount,
      wen: wenCount,
      eduType: selectedData.eduType.join(','),
      firstSelect,
      localBatchName: currentScoreType.localBatchName,
      provinceId: provinceId,
      // province,
      schoolProvinceId: selectedData.province.join(','),
      schoolType: selectedData.schoolType.join(','),
      score,
      specialtyIds,
      ranking,
      secondSelect: secondSelect.replaceAll('/', ','),
      active: selectedData.volunteer,
      year: wx.getStorageSync('year')
    }
    if (currentScoreType[selectedData.volunteer]) {
      const array = currentScoreType[selectedData.volunteer].split(':')
      params['chong'] = array[0]
      params['wen'] = array[1]
      params['bao'] = array[2]
    }
    let obj = wx.getStorageSync('school_label_obj')
    let newObj = {}
    selectedData.schoolLabel.map(e => {
      if (obj[e]) {
        newObj[obj[e]] = 1
      }
    })
    params = Object.assign(newObj, params)
    params = filterObj(params)
    const {result} = await decodeUserInfo()
    if (result.vips.length <= 0) {
      wx.navigateTo({
        url: '/pages/article/vip/index?params=' + encodeURIComponent(JSON.stringify(params)),
      })
    } else {
      wx.navigateTo({
        url: '/pages/volunteer/loading/index?params=' + encodeURIComponent(JSON.stringify(params)),
      })
    }




  }),
  inputChange(e) {
    const {
      type
    } = e.currentTarget.dataset
    this.setData({
      [type]: e.detail.value
    })
  },
  choose(e) {
    const key = e.currentTarget.dataset.key
    this.setData({
      visible: true,
      selectedKey: key
    })
  },


  goto(e) {
    const {
      url
    } = e.currentTarget.dataset
    wx.navigateTo({
      url,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '德道升学',
      path: '/pages/volunteer/index/index?scene=' + wx.getStorageSync('userInfo').id,
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  },
})